// application/service/BatchImportService.java
package com.library.bookservice.application.service;

import com.library.bookservice.adapter.rest.BatchImportRequest;
import com.library.bookservice.adapter.rest.BatchImportResponse;
import com.library.bookservice.domain.model.Book;
import com.library.bookservice.domain.port.BatchImportServicePort;
import com.library.bookservice.domain.port.BookRepositoryPort;
import com.library.bookservice.domain.exception.BookAlreadyExistsException;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 批量导入服务实现
 * 处理Excel数据批量导入的业务逻辑
 */
@Service
public class BatchImportService implements BatchImportServicePort {

    private final BookRepositoryPort bookRepository;

    public BatchImportService(BookRepositoryPort bookRepository) {
        this.bookRepository = bookRepository;
    }

    @Override
    public BatchImportResponse importBooks(BatchImportRequest request) {
        List<BatchImportResponse.ImportFailure> failures = new ArrayList<>();
        int successCount = 0;
        int rowIndex = 0;

        for (BatchImportRequest.BookImportItem item : request.books()) {
            rowIndex++;
            try {
                // 验证数据
                validateBookItem(item);

                // 检查是否已存在
                if (bookRepository.existsByIsbn(item.isbn())) {
                    throw new BookAlreadyExistsException("ISBN为 " + item.isbn() + " 的图书已存在");
                }

                // 创建图书
                LocalDate publicationDate = LocalDate.parse(item.publicationDate());
                Book book = new Book(
                        item.isbn(),
                        item.title(),
                        item.author(),
                        item.genre(),
                        publicationDate,
                        item.totalCopies()
                );

                bookRepository.save(book);
                successCount++;

            } catch (Exception e) {
                failures.add(new BatchImportResponse.ImportFailure(
                        rowIndex,
                        item.isbn(),
                        e.getMessage()
                ));
            }
        }

        return new BatchImportResponse(successCount, failures.size(), failures);
    }

    /**
     * 验证图书导入数据
     * @param item 待验证的图书数据项
     */
    private void validateBookItem(BatchImportRequest.BookImportItem item) {
        if (item.isbn() == null || item.isbn().trim().isEmpty()) {
            throw new IllegalArgumentException("ISBN不能为空");
        }
        if (item.isbn().length() < 10 || item.isbn().length() > 20) {
            throw new IllegalArgumentException("ISBN长度必须在10-20个字符之间");
        }
        if (item.title() == null || item.title().trim().isEmpty()) {
            throw new IllegalArgumentException("书名不能为空");
        }
        if (item.title().length() > 100) {
            throw new IllegalArgumentException("书名长度不能超过100个字符");
        }
        if (item.author() == null || item.author().trim().isEmpty()) {
            throw new IllegalArgumentException("作者不能为空");
        }
        if (item.author().length() > 50) {
            throw new IllegalArgumentException("作者名长度不能超过50个字符");
        }
        if (item.genre() == null || item.genre().trim().isEmpty()) {
            throw new IllegalArgumentException("分类不能为空");
        }
        if (item.publicationDate() == null) {
            throw new IllegalArgumentException("出版日期不能为空");
        }
        try {
            LocalDate.parse(item.publicationDate());
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("出版日期格式无效，期望格式：YYYY-MM-DD");
        }
        if (item.totalCopies() == null) {
            throw new IllegalArgumentException("总数量不能为空");
        }
        if (item.totalCopies() < 1 || item.totalCopies() > 1000) {
            throw new IllegalArgumentException("总数量必须在1-1000之间");
        }
    }
}